package com.panda.web.service.wechatinfo.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.panda.web.domain.dto.wechatinfo.EnshrineJobDTO;
import com.panda.web.domain.vo.wechatinfo.EnshrineJobVO;
import com.panda.web.entity.py.Company;
import com.panda.web.entity.py.Job;
import com.panda.web.entity.wechatinfo.EnshrineJob;
import com.panda.web.mapper.py.CompanyMapper;
import com.panda.web.mapper.py.JobMapper;
import com.panda.web.mapper.wechatinfo.EnshrineJobMapper;
import com.panda.web.service.wechatinfo.IEnshrineJobService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import com.panda.web.utils.pageutils.PageResult;
import org.springframework.transaction.annotation.Transactional;


/**
 * 岗位收藏Service业务层处理
 *
 * @author cpanda
 * @date 2025-07-19
 */
@Slf4j
@Service
public class EnshrineJobServiceImpl extends ServiceImpl<EnshrineJobMapper, EnshrineJob> implements IEnshrineJobService {
    @Autowired
    EnshrineJobMapper enshrineJobMapper;
    @Autowired
    JobMapper jobMapper;
    @Autowired
    CompanyMapper companyMapper;

    /**
     * 分页查询
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<EnshrineJobVO> PageList(EnshrineJobDTO dto, Integer pageNum, Integer pageSize) {

        Page<EnshrineJob> page = new Page<>(pageNum, pageSize);
        QueryWrapper<EnshrineJob> queryWrapper = new QueryWrapper();//需要处理查询条件
        if (dto.getOpenid()!=null){
            queryWrapper.eq("openid",dto.getOpenid());
        }
        queryWrapper.orderByDesc("creation_time");//收藏时间倒序
        IPage<EnshrineJob> jobIPage = enshrineJobMapper.selectPage(page, queryWrapper);
        long total = jobIPage.getTotal();
        List<EnshrineJob> records = jobIPage.getRecords();
        List<EnshrineJobVO> voList = jobVoToList(records);//封装vo数据方法

        return new PageResult<>(voList, total, pageNum, pageSize);
    }

    /**
     * 无分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public List<EnshrineJobVO> choiceList(EnshrineJobDTO dto) {
        QueryWrapper<EnshrineJob> queryWrapper = new QueryWrapper();//需要处理查询条件
        //构建查询条件
        List<EnshrineJob> jobList = enshrineJobMapper.selectList(queryWrapper);
        List<EnshrineJobVO> voList = jobVoToList(jobList);//封装vo数据方法
        return voList;
    }

    /**
     * 岗位收藏新增
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public synchronized int insert(EnshrineJobDTO dto) throws ParseException {
        EnshrineJob vo = new EnshrineJob();
        Long joId = dto.getJoId();
        String openid = dto.getOpenid();

        if (Objects.equals(dto.getEnshrineStatus(),"1")){//收藏
            Job job = jobMapper.selectById(joId);
            BeanUtils.copyProperties(job, vo);
            vo.setOpenid(openid);
            vo.setJoId(job.getId());
            if (!Objects.equals(job.getNatureCn(),null)){
                vo.setJobNature(job.getNatureCn());
            }
            String endTime = formatDate(vo.getEndTime());
            vo.setEndTime(endTime);
            if (Objects.equals(job.getEndTime(), "0")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String startTime = vo.getStartTime();
                Date startDate = sdf.parse(startTime);
                // 使用 Calendar 类来加上 3 个月
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startDate);
                calendar.add(Calendar.MONTH, 3); // 加 3 个月
                // 将新的时间格式化为字符串
                String newEndTime = sdf.format(calendar.getTime());
                vo.setEndTime(newEndTime);
            }
            String startTime = formatDate(vo.getStartTime());
            vo.setStartTime(startTime);
            String crawlingPlatform = job.getCrawlingPlatform();

            if (Objects.equals(crawlingPlatform, "") || Objects.equals(crawlingPlatform, null)) {
                vo.setWebsite("www.iguopin.com/job/detail?id=" + job.getJobId());
            } else if (Objects.equals(crawlingPlatform, "菜鸟")) {
                vo.setWebsite(job.getSource());
            } else {
                vo.setWebsite("www.ncss.cn/student/jobs/" + job.getJobId() + "/detail.html");
            }
            String companyId = job.getCompanyId();
            List<Company> companyList = companyMapper.findByCompanyId(companyId);
            String districtList = job.getDistrictList();
            // 创建 Gson 对象
            Gson gson = new Gson();
            String areaCn = null;
            if (!Objects.equals(districtList, null) && !Objects.equals(districtList, "")) {
                String areaChList = getAreaCnList(districtList);
                vo.setAreaCn(areaChList);
            } else {
                if (companyList != null && !companyList.isEmpty()) {// 如果 districtList 为 null，使用 companyList
                    areaCn = companyList.get(0).getAreaCn();
                }
                vo.setAreaCn(areaCn);
            }
            if (companyList != null && !companyList.isEmpty()) {
                vo.setComId(companyList.get(0).getId());
                vo.setIndustryCn(companyList.get(0).getIndustryCn());
                vo.setCompanyId(companyList.get(0).getCompanyId());
                vo.setCompanyName(companyList.get(0).getName());
                vo.setNatureCn(companyList.get(0).getNatureCn());
                vo.setShowLogo(companyList.get(0).getShowLogo());
            }
            Date date = new Date();
            vo.setCreationTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            enshrineJobMapper.insert(vo);
        }else {//取消收藏
            enshrineJobMapper.deleteByOpenidAndJobId(openid,joId);
        }
        return 1;
    }

    public static String getAreaCnList(String districtListJson) {
        try {
            // Create an ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();

            // Parse the JSON into a JsonNode
            JsonNode rootNode = objectMapper.readTree(districtListJson.replace("'", "\""));

            // Check if the root is an array
            if (rootNode.isArray()) {
                // If it's an array, process it as a list of objects
                List<Map<String, String>> list = objectMapper.convertValue(rootNode, List.class);

                // Using Java 8 Stream API to map and join area_cn fields
                String result = list.stream()
                        .map(item -> (String) item.get("area_cn"))
                        .collect(Collectors.joining(","));

                return result;
            } else {
                // If it's a single object (not an array), process it directly
                String areaCn = rootNode.path("area_cn").asText();
                return areaCn != null ? areaCn : "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    // 处理VO数据封装
    private List<EnshrineJobVO> jobVoToList(List<EnshrineJob> jobList) {
        List<EnshrineJobVO> voList = new ArrayList<>();
        if (jobList.size() > 0 && !jobList.isEmpty()) {
            for (EnshrineJob job : jobList) {
                EnshrineJobVO vo = new EnshrineJobVO();
                BeanUtils.copyProperties(job, vo);
                if (!Objects.equals(vo.getMajorCn(), null)) {
                    String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                    if (!majorCn.isEmpty()) {
                        // 按逗号分隔，并过滤掉空字符串
                        List<String> list = Arrays.stream(majorCn.split(","))
                                .map(String::trim) // 去除每个元素的前后空格
                                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                                .collect(Collectors.toList());
                        vo.setMajorList(list);
                    } else {
                        vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                    }
                } else {
                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                }
                voList.add(vo);
            }
        }
        return voList;
    }

    public static String formatDate(String inputDate) {
        if (inputDate == null || inputDate.trim().isEmpty() || inputDate.equals("0")) {
            return "";
        }
        // 定义输入格式（"yyyy-MM-dd HH:mm:ss"）
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 定义输出格式（"M月d日"）
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            // 解析输入的日期字符串
            Date date = inputFormat.parse(inputDate);
            // 返回格式化后的日期字符串
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;  // 返回null表示解析失败
        }
    }

}